package com.lfy.modules.safety.limit;

import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;

import java.util.concurrent.TimeUnit;

/**
 * 本地限流器
 *
 * @author <a href="https://www.lvfeiy.top">lvfeiyang</a>
 * @date 2024/4/24 19:36
 */
public class limitLocal extends BaseLimit{
    private final   Cache<String, Limit> LIMIT_CACHE;
    public limitLocal() {
        LIMIT_CACHE =  Caffeine.newBuilder()
                .expireAfterAccess(4, TimeUnit.HOURS)
                .maximumSize(10_000)
                .build();
    }

    @Override
    public Integer getCount(String key,long time) {
        Limit limit = LIMIT_CACHE.get(key, (v) -> new Limit());
        long nowTime = System.currentTimeMillis();

        assert limit != null;

        return  limit.getCount(nowTime - time);
    }

    @Override
    public void setCount(String key) {
        Limit limit = LIMIT_CACHE.get(key, (v) -> new Limit());
        assert limit != null;
        limit.setCount();
    }



}
